<template>
  <div class="workflow-templates-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>流程模板管理</span>
          <el-button type="primary" @click="createTemplate">创建新模板</el-button>
        </div>
      </template>
      
      <el-table :data="templates" style="width: 100%" v-loading="loading">
        <el-table-column prop="name" label="模板名称" width="180" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'published' ? 'success' : 'warning'">
              {{ scope.row.status === 'published' ? '已发布' : '草稿' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="version" label="版本" width="80" />
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250">
          <template #default="scope">
            <el-button-group>
              <el-button 
                type="primary" 
                size="small" 
                @click="viewTemplate(scope.row)"
                text
              >
                查看
              </el-button>
              <el-button 
                v-if="scope.row.status === 'draft'" 
                type="primary" 
                size="small" 
                @click="editTemplate(scope.row)"
                text
              >
                编辑
              </el-button>
              <el-button 
                v-if="scope.row.status === 'draft'" 
                type="warning" 
                size="small" 
                @click="publishTemplate(scope.row)"
                text
              >
                发布
              </el-button>
              <el-button 
                v-if="scope.row.status === 'published'" 
                type="success" 
                size="small" 
                @click="createInstance(scope.row)"
                text
              >
                创建流程
              </el-button>
              <el-button 
                v-if="scope.row.status === 'draft'" 
                type="danger" 
                size="small" 
                @click="deleteTemplate(scope.row)"
                text
              >
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 创建流程实例对话框 -->
    <el-dialog v-model="createDialogVisible" title="创建流程实例" width="500px">
      <el-form :model="instanceForm" label-width="120px">
        <el-form-item label="流程类型">
          <el-input v-model="instanceForm.type" disabled></el-input>
        </el-form-item>
        <el-form-item label="变量配置">
          <el-input
            v-model="instanceForm.variablesString"
            type="textarea"
            rows="5"
            placeholder="请输入JSON格式的流程变量，例如: {&quot;key&quot;: &quot;value&quot;}"
          ></el-input>
          <div class="form-tip">JSON格式的流程初始变量</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCreateInstance">创建</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';

const router = useRouter();
const templates = ref([]);
const loading = ref(false);
const createDialogVisible = ref(false);
const instanceForm = ref({
  templateId: null,
  type: '',
  variablesString: '{}'
});

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString);
  return date.toLocaleString();
};

// 获取模板列表
const fetchTemplates = async () => {
  loading.value = true;
  try {
    const response = await axios.get('/workflow/templates');
    templates.value = response.data;
  } catch (error) {
    console.error('获取模板列表失败:', error);
    ElMessage.error('获取模板列表失败');
  } finally {
    loading.value = false;
  }
};

// 创建新模板
const createTemplate = () => {
  router.push('/workflow-editor');
};

// 查看模板
const viewTemplate = (template) => {
  router.push(`/workflow-template/${template.id}`);
};

// 编辑模板
const editTemplate = (template) => {
  router.push(`/workflow-editor/${template.id}`);
};

// 发布模板
const publishTemplate = async (template) => {
  try {
    await ElMessageBox.confirm(
      '发布后将不能修改模板，如需更改将创建新版本。确定要发布此模板吗？',
      '发布确认',
      {
        confirmButtonText: '确定发布',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    await axios.post(`/workflow/templates/${template.id}/publish`);
    ElMessage.success('模板发布成功');
    await fetchTemplates(); // 刷新列表
  } catch (error) {
    if (error !== 'cancel') {
      console.error('发布模板失败:', error);
      ElMessage.error(`发布模板失败: ${error.response?.data?.message || '未知错误'}`);
    }
  }
};

// 删除模板
const deleteTemplate = async (template) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除此模板吗？此操作不可恢复',
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'danger'
      }
    );
    
    await axios.delete(`/workflow/templates/${template.id}`);
    ElMessage.success('模板删除成功');
    await fetchTemplates(); // 刷新列表
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除模板失败:', error);
      ElMessage.error(`删除模板失败: ${error.response?.data?.message || '未知错误'}`);
    }
  }
};

// 打开创建流程实例对话框
const createInstance = (template) => {
  instanceForm.value = {
    templateId: template.id,
    type: template.name,
    variablesString: '{}'
  };
  createDialogVisible.value = true;
};

// 提交创建流程实例
const submitCreateInstance = async () => {
  try {
    // 解析JSON字符串为对象
    let variables = {};
    try {
      variables = JSON.parse(instanceForm.value.variablesString);
    } catch (e) {
      return ElMessage.error('变量格式错误，请输入有效的JSON');
    }
    
    const response = await axios.post('/workflow/create', {
      template_id: instanceForm.value.templateId,
      type: instanceForm.value.type,
      variables: variables
    });
    
    ElMessage.success('流程创建成功');
    createDialogVisible.value = false;
    
    // 重定向到流程详情页
    router.push(`/workflow/${response.data.workflow_id}`);
  } catch (error) {
    console.error('创建流程实例失败:', error);
    ElMessage.error(`创建流程实例失败: ${error.response?.data?.message || '未知错误'}`);
  }
};

onMounted(() => {
  fetchTemplates();
});
</script>

<style scoped>
.workflow-templates-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
</style> 